﻿Imports OpenNETCF.WindowsCE.Notification

Public Class Form1
  Private _timeouts As New List(Of Integer)
  Private _doVibrate As Boolean = True
  Private _advanced As Boolean = False
  Private _setat As Boolean = False
  Private _curTimeout As Integer = 15
  Private _filename As String = Me.ApplicationPath & "\settings.ini"
  Private _exists As TimerExists = Nothing
  Private _curIni As New AvianWaves.Ini.File

  Public Sub New()
    InitializeComponent()

    If IO.File.Exists(Me._filename) Then
      Me._curIni.LoadFile(Me._filename)
    End If

    Me.ReloadIni()

    If Me._advanced Then
      Me.MenuItemAdvanced_Click(Me, EventArgs.Empty)
    End If

    If Me._setat Then
      Me.WP7ButtonExact_Click(Me, New MouseEventArgs(Windows.Forms.MouseButtons.Left, 1, 0, 0, 0))
    End If

    Dim dt As Date = Me.ExistingMute4Timer
    If dt > Date.MinValue Then
      Me._exists = New TimerExists(dt)
      Me._exists.Dock = DockStyle.Fill
      Me.Controls.Add(Me._exists)
      Me._exists.BringToFront()
      Me.MenuItemSet.Enabled = False
      Me.MenuItemAdvanced.Enabled = False
      AddHandler Me._exists.CancelClicked, AddressOf Exists_CancelClicked
    End If

    Me.DateTimePickerDate.Value = Date.Now
    Me.DateTimePickerTime.Value = Date.Now.AddMinutes(30)

    Me.NumericUpDownMinutes.Maximum = Integer.MaxValue
  End Sub

  Private Sub ReloadIni()
    Dim doSave As Boolean = False

    Me._timeouts.Clear()

    If Me._curIni.Section("Settings") Is Nothing Then
      Me._curIni.AddSection("Settings")
    End If

    With Me._curIni.Section("Settings")
      Me._doVibrate = .BooleanValueNoNull("VibrateIsDefault", True)
      Me._curTimeout = .IntegerValueNoNull("CurrentTimeout", 15)
      Me._advanced = .BooleanValueNoNull("Advanced", False)
      Me._setat = .BooleanValueNoNull("SetAt", False)
    End With

    If Me._curIni.Section("Timeouts") Is Nothing Then
      Me._curIni.AddSection("Timeouts")
      Me._curIni.Section("Timeouts").IntegerValue("T1") = 15
      Me._curIni.Section("Timeouts").IntegerValue("T2") = 30
      Me._curIni.Section("Timeouts").IntegerValue("T3") = 60
      Me._curIni.Section("Timeouts").IntegerValue("T4") = 120
      Me._curIni.Section("Timeouts").IntegerValue("T5") = 180
      doSave = True
    End If

    With Me._curIni.Section("Timeouts")
      For Each k As String In .Keys
        Dim x As Integer = .IntegerValueNoNull(k)
        If x > 0 Then
          Me._timeouts.Add(x)
        End If
      Next
    End With

    If Me._timeouts.Count <= 0 Then
      Me._timeouts.Add(15)
      Me._timeouts.Add(30)
      Me._timeouts.Add(60)
      Me._timeouts.Add(120)
      Me._timeouts.Add(180)
    End If

    Me._timeouts.Sort()

    If Not Me._timeouts.Contains(Me._curTimeout) Then
      Me._curTimeout = Me._timeouts(0)
      Me._curIni.Section("Settings").IntegerValue("CurrentTimeout") = Me._curTimeout
      doSave = True
    End If

    Me.SetWP7ButtonProfileText()
    Me.SetWP7ButtonTimeoutText()

    If doSave Then
      Me.SaveIni()
    End If
  End Sub

  Private Sub MenuItemSet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItemSet.Click
    If Me.SetMute4Timer() Then
      If Me._doVibrate Then
        ' Set to vibrate profile
        SetProfile.SetProfileVibrate()
      Else
        ' Set to silent profile
        SetProfile.SetProfileMuted()
      End If

      Me._curIni.Section("Settings").Add("VibrateIsDefault", Me._doVibrate)
      Me._curIni.Section("Settings").Add("CurrentTimeout", Me._curTimeout)
      Me._curIni.Section("Settings").Add("Advanced", Me._advanced)
      Me._curIni.Section("Settings").Add("SetAt", Me._setat)

      Me.SaveIni()
      Me.Close()
    End If
  End Sub

  Private Sub MenuItemCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItemCancel.Click
    Me.Close()
  End Sub

  Private Sub WP7ButtonProfile_MouseDown(ByVal sender As System.Object, ByVal e As MouseEventArgs) Handles WP7ButtonProfile.MouseDown, WP7ButtonProfile2.MouseDown
    Me._doVibrate = Not Me._doVibrate
    Me.SetWP7ButtonProfileText()
  End Sub

  Private Sub WP7ButtonTime_MouseDown(ByVal sender As System.Object, ByVal e As MouseEventArgs) Handles WP7ButtonTime.MouseDown
    If Me._timeouts IsNot Nothing AndAlso Me._timeouts.Count > 0 Then
      Dim lastTimeout As Integer = Me._curTimeout

      For Each i As Integer In Me._timeouts
        If i > Me._curTimeout Then
          Me._curTimeout = i
          Exit For
        End If
      Next

      If lastTimeout = Me._curTimeout Then
        Me._curTimeout = Me._timeouts(0)
      End If

      Me.SetWP7ButtonTimeoutText()
    End If
  End Sub

  Private Sub SetWP7ButtonProfileText()
    If Me._doVibrate Then
      Me.WP7ButtonProfile.Text = "Vibrate"
      Me.WP7ButtonProfile2.Text = "Vibrate"
    Else
      Me.WP7ButtonProfile.Text = "Silent"
      Me.WP7ButtonProfile2.Text = "Silent"
    End If
  End Sub

  Private Sub SetWP7ButtonTimeoutText()
    Dim h As Integer = Math.Floor(Me._curTimeout / 60)
    Dim m As Integer = Me._curTimeout Mod 60

    Dim text As String = ""

    If h > 1 Then
      text = h.ToString & " hours "
    ElseIf h = 1 Then
      text = h.ToString & " hour "
    End If

    If m > 1 Then
      text &= m.ToString & " minutes"
    ElseIf m = 1 Then
      text &= m.ToString & " minute"
    End If

    Me.WP7ButtonTime.Text = text
    Me.NumericUpDownMinutes.Value = CDec(Me._curTimeout)
  End Sub

  Private ReadOnly Property ApplicationPath() As String
    Get
      Return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly.GetName.CodeBase)
    End Get
  End Property

  Private Sub Exists_CancelClicked()
    If Me._exists IsNot Nothing Then
      If Me.DeleteAllMute4Timers() Then
        Me.Controls.Remove(Me._exists)
        Me.MenuItemSet.Enabled = True
        Me.MenuItemAdvanced.Enabled = True
        RemoveHandler Me._exists.CancelClicked, AddressOf Exists_CancelClicked
        Me._exists = Nothing
        SetProfile.SetProfileNormal()
      End If
    End If
  End Sub

  Private ReadOnly Property ExistingMute4Timer() As Date
    Get
      Dim notFinished As Boolean = True
      Dim errorCount As Integer = 0

      While notFinished
        Try
          For Each i As Integer In Notify.GetUserNotificationHandles
            With Notify.GetUserNotification(i).UserNotificationTrigger
              If .Application IsNot Nothing AndAlso String.Compare(.Application, Me.SetNormalProfilePath, True) = 0 Then
                Return .StartTime
              End If
            End With
          Next

          notFinished = False
        Catch
          errorCount += 1

          If errorCount > 20 Then
            If MessageBox.Show("Mute4 is unable to enumerate the Notification Queue.  You may need to soft reset your device before running Mute4 again.  This is not a normal condition and can indicate instability in the OS.  Try again?", "Mute4", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1) = Windows.Forms.DialogResult.Yes Then
              errorCount = 0
            Else
              Return Date.MinValue
            End If
            Application.DoEvents()
          Else
            Threading.Thread.Sleep(150)
          End If
        End Try
      End While

      Return Date.MinValue
    End Get
  End Property

  Private Function DeleteAllMute4Timers() As Boolean
    Me._exists.CancelButtonEnabled = False
    Application.DoEvents()

    Dim notFinished As Boolean = True
    Dim errorCount As Integer = 0

    While notFinished
      Try
        Dim notifs As New List(Of Integer)

        For Each i As Integer In Notify.GetUserNotificationHandles
          With Notify.GetUserNotification(i).UserNotificationTrigger
            If .Application IsNot Nothing AndAlso String.Compare(.Application, Me.SetNormalProfilePath, True) = 0 Then
              notifs.Add(i)
            End If
          End With
        Next

        For Each i As Integer In notifs
          Notify.ClearUserNotification(i)
        Next

        notFinished = False
      Catch
        errorCount += 1

        If errorCount > 20 Then
          If MessageBox.Show("Mute4 is unable to clear itself from the Notification Queue.  You may need to soft reset your device before running Mute4 again.  This is not a normal condition and can indicate instability in the OS.  Try again?", "Mute4", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1) = Windows.Forms.DialogResult.Yes Then
            errorCount = 0
          Else
            Me._exists.CancelButtonEnabled = True
            Return False
          End If
          Application.DoEvents()
        Else
          Threading.Thread.Sleep(150)
        End If

      End Try
    End While

    Return True
  End Function

  Private ReadOnly Property SetNormalProfilePath() As String
    Get
      Static appname As String = ApplicationPath & "\SetNormalProfile.exe"
      Return appname
    End Get
  End Property

  Private Function SetMute4Timer() As Boolean
    If Me.PanelBasic.Enabled Then
      Notify.RunAppAtTime(Me.SetNormalProfilePath, Date.Now.AddMinutes(Me._curTimeout))
    Else
      If Me.PanelSetAt.Enabled Then
        Dim setat As DateTime = New Date(Me.DateTimePickerDate.Value.Year, Me.DateTimePickerDate.Value.Month, Me.DateTimePickerDate.Value.Day, Me.DateTimePickerTime.Value.Hour, Me.DateTimePickerTime.Value.Minute, Me.DateTimePickerTime.Value.Second)
        If setat > DateTime.Now Then
          Notify.RunAppAtTime(Me.SetNormalProfilePath, setat)
        Else
          MessageBox.Show("The time being set is in the past.  The timeout value must be in the future.", "Mute4", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
          Return False
        End If
      Else
        Notify.RunAppAtTime(Me.SetNormalProfilePath, Date.Now.AddMinutes(CDbl(NumericUpDownMinutes.Value)))
      End If
    End If

    Return True
  End Function

  Private Sub LinkLabel1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LinkLabel1.Click, LinkLabel2.Click
    If MessageBox.Show("Would you like to visit the project home page in the default browser on your device?", "Mute4", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
      Process.Start("http://forum.xda-developers.com/showthread.php?p=6560139#post6560139", "")
    End If
  End Sub

  Private Sub MenuItemAdvanced_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItemAdvanced.Click
    If Me.PanelBasic.Enabled Then
      Me.MenuItemAdvanced.Text = "Basic"
      Me.PanelAdvanced.Enabled = True
      Me.PanelAdvanced.Visible = True
      Me.PanelAdvanced.BringToFront()
      Me.PanelBasic.Enabled = False
      Me.PanelBasic.Visible = False
      Me._advanced = True
    Else
      Me.MenuItemAdvanced.Text = "Advanced"
      Me.PanelBasic.Enabled = True
      Me.PanelBasic.Visible = True
      Me.PanelBasic.BringToFront()
      Me.PanelAdvanced.Enabled = False
      Me.PanelAdvanced.Visible = False
      Me._advanced = False
    End If
  End Sub

  Private Sub MenuItemSettings_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItemSettings.Click
    Dim st As New Settings
    st.SetIni(Me._curIni)

    If st.ShowDialog = Windows.Forms.DialogResult.OK Then
      Me.SaveIni()
      Me.ReloadIni()
    End If
  End Sub

  Private Sub SaveIni()
    Dim attr As New IO.FileInfo(Me._filename)
    attr.Attributes = IO.FileAttributes.Normal
    Me._curIni.Save(Me._filename, True)
  End Sub

  Private Sub WP7ButtonExact_Click(ByVal sender As System.Object, ByVal e As MouseEventArgs) Handles WP7ButtonExact.MouseDown
    Me.PanelSetAt.Enabled = True
    Me.PanelSetAt.Visible = True
    Me.PanelSetAt.BringToFront()
    Me.PanelSetTo.Enabled = False
    Me.PanelSetTo.Visible = False
    Me._setat = True
  End Sub

  Private Sub WP7ButtonToggleAt_Click(ByVal sender As System.Object, ByVal e As MouseEventArgs) Handles WP7ButtonToggleAt.MouseDown
    Me.PanelSetTo.Enabled = True
    Me.PanelSetTo.Visible = True
    Me.PanelSetTo.BringToFront()
    Me.PanelSetAt.Enabled = False
    Me.PanelSetAt.Visible = False
    Me._setat = False
  End Sub
End Class
